package com.hjs.pacloud.Controller;

import com.hjs.pacloud.service.IFiletransferService;
import java.io.IOException;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @auther hanjinsong
 * @create 2019-08-05 10:28
 */

@Controller
public class FileuploadController {

    private Logger logger = LoggerFactory.getLogger(FileuploadController.class);

    @Autowired
    private IFiletransferService iFiletransferService;


    @GetMapping("/")
    public String listUploadedFiles(Model model) throws IOException {

        Model model1 = model.addAttribute("files", iFiletransferService.loadAll().map(
                path -> MvcUriComponentsBuilder.fromMethodName(FileuploadController.class,
                        "serveFile", path.getFileName().toString()).build().toString()
        ).collect(Collectors.toList()));
        logger.info(model1.toString());
        return "index";
    }

    @GetMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

        Resource file = iFiletransferService.loadAsResource(filename);
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + file.getFilename() + "\"").body(file);
    }

    @PostMapping("/")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {

        iFiletransferService.store(file);
        redirectAttributes.addFlashAttribute("message",
                "You successfully uploaded " + file.getOriginalFilename() + "!");

        return "redirect:/";
    }

}
